<template>
  <el-form :model="form" label-width="auto" @keydown.enter.prevent="getData">
    <el-row :gutter="12">
      <el-col :span="8">
        <el-form-item label="图文标题">
          <el-input v-model="form.title" placeholder="请输入图文标题" @blur="nameBlur" clearable></el-input>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>

  <div>
    <el-button type="primary" :disabled="!props.editInfo.id" style="margin-right: 10px"
      @click="handleAddVideo">新增图文</el-button>
    <el-button type="danger" :disabled="selectIds.length === 0" @click="batchDelete">批量取消</el-button>
    <el-button type="primary" @click="syncImgText">
      <el-icon>
        <Refresh />
      </el-icon>
      同步图文课程
    </el-button>
  </div>

  <art-table :data="tableData" :loading="tableLoading" :currentPage="pageNum" :pageSize="pageSize" :total="pageTotal"
    @current-change="currentChange" @size-change="sizeChange" @selection-change="handleSelectionChange">
    <template #default>
      <el-table-column type="selection" width="55" />
      <!-- <el-table-column label="ID" prop="id" width="120" /> -->
      <!-- <el-table-column label="排序" prop="sort" width="100" /> -->
      <el-table-column prop="sort" label="排序" width="160" #default="scope">
        <span v-if="editRowSort !== scope.$index">{{ scope.row.sort }}</span>
        <el-input v-else v-model="scope.row.sort" maxlength="6" show-word-limit style="width: 110px"
          @keydown.enter="submitSort(scope.row.id, scope.row.sort)" />
        <i v-if="editRowSort !== scope.$index" class="iconfont-sys edit-icon"
          @click="editRowSort = editRowSort === scope.$index ? -1 : scope.$index">&#xe65f;</i>
        <i v-else class="iconfont-sys edit-icon" @click="submitSort(scope.row.id, scope.row.sort)">&#xe616;</i>
      </el-table-column>
      <!-- 视频内容 -->
      <el-table-column label="图文标题" prop="title" width="400">
        <template #default="scope">
          <div class="title_box">
            <div class="title_box_right">
              <div class="bankcont_title">
                <div class="bankcont_title_text">{{ scope.row.title }}</div>
              </div>
              <div style="clear: both"></div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="封面图" prop="coverUrl" width="300">
        <template #default="scope">
          <div>
            <el-image v-if="scope.row.coverUrl" :src="scope.row.coverUrl" class="tableimg"
              :preview-src-list="[scope.row.coverUrl]" :preview-teleported="true" fit="cover"
              :hide-on-click-modal="true" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="图文描述" prop="subtitle" width="300" />
      <!-- 视频链接 -->
      <el-table-column #default="scope" label="是否启用">
        <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" @change="editPay(scope.row)" />
      </el-table-column>

      <el-table-column label="操作时间" prop="updateTime">
        <template #default="scope">
          {{ scope.row.updateTime }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="150">
        <template #default="scope">
          <button-table type="edit" @click="buttonMoreClick(scope.row)" />
          <button-table type="delete" @click="handleDel(scope.row.id)" />
        </template>
      </el-table-column>
    </template>
  </art-table>

  <add-image-text-dialog v-if="showAddVideoDialog" :show-add-video-visible="showAddVideoDialog" :group-info="editInfo"
    :edit-info="editData" @close-dialog="closeSelectionDialog" />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { getArticleList, delArticleList, editArticleList, syncArticleGroupList } from '@/api/questionbank'
import AddImageTextDialog from './addImageTextDialog.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps({
  showQuestionDetailVisible: {
    type: Boolean
  },
  editInfo: {
    type: Object,
    default: () => {
      return { id: '' }
    }
  },
  groupId: {
    type: String
  }
})
console.log(props.groupId, "groupId===");

const editRowSort = ref(-1)

const emit = defineEmits(['uploadGroup'])

const tableData = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
const tableLoading = ref(false)
const selectIds = ref<string[]>([])
const showAddVideoDialog = ref(false)
const editData = ref({})
const groupId = ref('')

const form = reactive({
  // questionType: '',
  title: ''
})

const currentChange = (val: number) => {
  pageNum.value = val
  getData()
}
const sizeChange = (val: number) => {
  pageSize.value = val
  pageNum.value = 1
  getData()
}

function handleSelectionChange(data: any[]) {
  selectIds.value = data.map((item) => item.id)
}

function batchDelete() {
  ElMessageBox.confirm('确定批量取消选择吗？', '确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    let ids = selectIds.value.join(',')
    handleDelete(ids)
  })
}

const syncImgText = async () => {
  const res = await syncArticleGroupList()
  if (res.code === '00000') {
    ElMessage.success('同步成功')
    await getData()
    emit('uploadGroup')
  }
}

function buttonMoreClick(item: any) {
  showAddVideoDialog.value = true
  editData.value = JSON.parse(JSON.stringify(item))
}

function handleDel(id: string) {
  ElMessageBox.confirm('确定删除吗？', '确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    handleDelete(id)
  })
}

async function editPay(row: any) {
  const res = await editArticleList(row.id, {
    status: row.status
  })
  if (res.code === '00000') {
    ElMessage.success('编辑成功')
    getData()
  }
}

async function handleDelete(ids: string) {
  try {
    const res = await delArticleList(ids)
    if (res.code === '00000') {
      await getData()
      emit('uploadGroup')
      selectIds.value = []
      ElMessage.success('删除成功')
    }
  } catch (e) {
  } finally {
  }
}

function handleAddVideo() {
  showAddVideoDialog.value = true
  editData.value = { id: '' }
}

async function closeSelectionDialog(value: boolean) {
  showAddVideoDialog.value = false
  if (value) {
    await getData()
    emit('uploadGroup')
  }
}

async function getData() {
  const obj: Record<string, any> = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    groupId: props.groupId
  }

  for (const key in form) {
    const typedKey = key as keyof typeof form
    if (form[typedKey] !== '') {
      obj[typedKey] = form[typedKey]
    }
  }

  try {
    tableLoading.value = true
    const res = await getArticleList(obj)
    if (res.code === '00000') {
      tableData.value = res.data.list
      pageTotal.value = res.data.total
    }
  } catch (e) {
  } finally {
    tableLoading.value = false
  }
}

const nameBlur = () => {
  pageNum.value = 1
  pageSize.value = 10
  getData()
}


const submitSort = async (id: string, sort: number) => {
  const res = await editArticleList(id, {
    sort
  })
  if (res.code === '00000') {
    ElMessage.success('修改成功')
    getData()
    editRowSort.value = -1
  }
}

onMounted(() => {
  getData()
})
</script>

<style scoped lang="scss">
.tableimg {
  width: 80px;
  height: 80px;
}

.edit-icon {
  margin-left: 4px;
  cursor: pointer;
  color: var(--el-color-primary);
}
</style>